/**
 * 公共路由表（不需要权限的路由，每个用户都可以看见，看见的内容都一样）
 */

import { notEmpty } from '~/utils/common.js'
import pathTable from './path_table.js'
import { customPublicRoutes } from '@/router/custom_public_routes.js'
// Portal
import Portal from '~/views/portal/index.vue'
import Login from '~/views/portal/login/index.vue'
import Register from '~/views/portal/register/index.vue'
import ResetPassword from '~/views/portal/reset_password/index.vue'
// Layout
import Layout from '~/views/layout/index.vue'
// Error
import Err401 from '~/views/errors/401.vue'
import Err404 from '~/views/errors/404.vue'
import Err500 from '~/views/errors/500.vue'

export const publicRoutes = [
  ...customPublicRoutes,
  {
    path: pathTable.PORTAL,
    redirect: pathTable.LOGIN,
    name: 'portal',
    component: Portal,
    children: [
      {
        path: pathTable.LOGIN,
        name: 'login',
        component: Login
      },
      {
        path: pathTable.REGISTER,
        name: 'register',
        component: Register
      },
      {
        path: pathTable.RESET_PASSWORD,
        name: 'reset_password',
        component: ResetPassword
      }
    ]
  },
  {
    path: pathTable.LAYOUT,
    name: 'layout',
    component: Layout,
    children: [
      {
        path: pathTable.NOT_AUTHORIZED_EMBEDDED,
        name: 'notAuthorizedEmbedded',
        component: Err401,
        meta: {
          isBreadcrumb: true,
          breadcrumbRedirect: true,
          title: '访问权限不足'
        }
      }
    ]
  },
  {
    path: pathTable.NOT_AUTHORIZED,
    name: 'notAuthorized',
    component: Err401
  },
  {
    path: pathTable.NOT_FOUND,
    name: 'notFound',
    component: Err404
  },
  {
    path: pathTable.NOT_CONNECTED,
    name: 'notConnect',
    component: Err500
  },
  // 不匹配时（即页面不存在）的路由
  {
    path: '/:catchAll(.*)',
    redirect: pathTable.NOT_FOUND,
    name: 'finalNotMatch'
  }
]

/**
 * 遍历提取publicRoutes中的路由name，形成列表
 */
export const publicRouteNames = (() => {
  function travelRouteTree(publicRouteNames, routeNode) {
    if (notEmpty(routeNode)) {
      if (routeNode.name && routeNode.name.length > 0) {
        publicRouteNames.push(routeNode.name)
      }
      if (notEmpty(routeNode.children)) {
        routeNode.children.forEach(childRoute => {
          travelRouteTree(publicRouteNames, childRoute)
        })
      }
    }
  }

  const publicRouteNames = []
  publicRoutes.forEach(rootRoute => {
    travelRouteTree(publicRouteNames, rootRoute)
  })
  return publicRouteNames
})()
